<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { StrUtil } from '@xtail/core'
  import { IconifyIcon, getIcon, loadIcon, addIcon } from '@iconify/vue'
  import { Icon as IconOffline } from '@iconify/vue/offline'
  import { IconIconifyOfflinePropsType } from './types'

  defineOptions({
    name: 'SIconIconifyOffline'
  })

  const props = withDefaults(defineProps<IconIconifyOfflinePropsType>(), {
    icon: '',
    width: 24,
    height: 24
  })

  const iconData = ref<IconifyIcon | string>(props.icon)
  const iconDataPreHandler = async () => {
    // 如果传入的图标为图标名称字符串
    if (StrUtil.isStr(props.icon)) {
      // 从本地图标存储数据中获取图标数据
      iconData.value = getIcon(props.icon) as IconifyIcon | string
      // 如果本地图标存储中没有该图标数据，则尝试从网络获取
      if (!iconData.value) {
        iconData.value = (await loadIcon(props.icon).catch(() => Promise.resolve(props.icon))) as
          | IconifyIcon
          | string
        // 如果网络获取成功
        if (!StrUtil.isStr(iconData.value)) {
          // 存储图标数据到本地图标存储
          addIcon(props.icon, iconData.value)
        }
      }
    } else {
      iconData.value = props.icon
    }
  }
  watch(
    () => props.icon,
    async () => await iconDataPreHandler(),
    { immediate: true }
  )
</script>

<template>
  <IconOffline
    :id="id"
    class="s-icon-iconify-offline"
    :class="className"
    :icon="iconData"
    :ssr="ssr"
    :mode="mode"
    :inline="inline"
    :width="width"
    :height="height"
    :color="color"
    :h-flip="hFlip"
    :v-flip="vFlip"
    :flip="flip"
    :rotate="rotate"
    :style="style"
    :on-load="onLoad"
    :customise="customise"
  />
</template>

<style lang="scss">
  @use './style' as *;
</style>
